//
//  JWRateStarView.m
//
//  Created by Xu Jiwei on 10-10-20.
//  Copyright 2010 Xujiwei.com. All rights reserved.
//

#import "JWRateStarView.h"

@implementation JWRateStarView

@synthesize rate;
@synthesize totalStarCount;
@synthesize yellowStar;
@synthesize grayStar;
@synthesize starGap;
@synthesize enableRate;


- (void)setup {
    totalStarCount = 10;
    
    self.yellowStar = [UIImage imageNamed:@"jw_rate_star_yellow.png"];
    self.grayStar = [UIImage imageNamed:@"jw_rate_star_gray.png"];
    
    self.rate = 0;
    self.backgroundColor = [UIColor clearColor];
    self.userInteractionEnabled = NO;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self setup];
    }
    
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        [self setup];
    }
    return self;
}


- (void)setTotalStarCount:(NSUInteger)count {
    NSAssert(count > 0, @"Star count must > 0");
    
    totalStarCount = count;
    
    [self setNeedsDisplay];
}


- (void)setRate:(float)r {
    rate = r <= totalStarCount ? r : totalStarCount;
    
    [self setNeedsDisplay];
}


- (void)setEnableRate:(BOOL)enable {
    enableRate = enable;
    self.userInteractionEnabled = enableRate;
}


- (UIImage *)imageForDraw:(UIImage *)image cropRect:(CGRect)cropRect {
    UIImage *retImage = image;
    
    CGRect rect = CGRectMake(0.0, 0.0, self.bounds.size.height, self.bounds.size.height);
    
    static float sysVer = 0.0;
    static float scale = 1.0;
    if (sysVer == 0.0) {
        sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
        if (sysVer >= 4.0) {
            scale = [[UIScreen mainScreen] scale];
        }
    }
    
    // Only scale image when image's size does not match target size
    if (!CGRectEqualToRect(CGRectMake(0, 0, image.size.width, image.size.height), rect)) {
        if (sysVer < 4.0) {
            UIGraphicsBeginImageContext(rect.size);
        } else {
            UIGraphicsBeginImageContextWithOptions(rect.size, NO, scale);
        }
        [image drawInRect:rect];
        retImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    
    if (!CGRectEqualToRect(cropRect, CGRectZero)) {
        // Create bitmap image from original image data,
        // using rectangle to specify desired crop area
        if (scale > 1.0) {
            cropRect.origin.x *= scale;
            cropRect.origin.y *= scale;
            cropRect.size.width *= scale;
            cropRect.size.height *= scale;
        }
        CGImageRef imageRef = CGImageCreateWithImageInRect([retImage CGImage], cropRect);
        if (sysVer < 4.0) {
            retImage = [UIImage imageWithCGImage:imageRef];
        } else {
            retImage = [UIImage imageWithCGImage:imageRef scale:scale orientation:UIImageOrientationUp];
        }
        CGImageRelease(imageRef);
    }
    
    return retImage;
}


- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    
    float starWidth = self.bounds.size.height;
    float totalWidth = starWidth * totalStarCount + starGap * (totalStarCount - 1);
    float left = floor((self.bounds.size.width - totalWidth) / 2.0);
    
    UIImage *yellowImg = [self imageForDraw:self.yellowStar cropRect:CGRectZero];
    UIImage *grayImg = [self imageForDraw:self.grayStar cropRect:CGRectZero];
    
    for (int i = 0; i < totalStarCount; ++i) {
        if (i < floor(rate)) {
            [yellowImg drawInRect:CGRectMake(left, 0, starWidth, starWidth)];
            
        } else if (i > floor(rate)) {
            [grayImg drawInRect:CGRectMake(left, 0, starWidth, starWidth)];
            
        } else {
            float yellowWidth = floor((rate - i) * starWidth);
            [[self imageForDraw:yellowImg cropRect:CGRectMake(0, 0, yellowWidth, starWidth)]
             drawInRect:CGRectMake(left, 0, yellowWidth, starWidth)];
            [[self imageForDraw:grayImg cropRect:CGRectMake(yellowWidth, 0, starWidth-yellowWidth, starWidth)]
             drawInRect:CGRectMake(left+yellowWidth, 0, starWidth-yellowWidth, starWidth)];
        }
        
        left += starWidth + starGap;
    }
}


- (void)changeRateWithLocation:(CGPoint)location {
    float starWidth = self.bounds.size.height;
    float totalWidth = starWidth * totalStarCount + starGap * (totalStarCount - 1);
    float left = floor((self.bounds.size.width - totalWidth) / 2.0);
    
    self.rate = location.x < left ? 0 : MIN(ceil((location.x - left) / (starWidth + starGap)), totalStarCount);
}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    if (enableRate) {
        [self changeRateWithLocation:[[touches anyObject] locationInView:self]];
    }
}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    if (enableRate) {
        [self changeRateWithLocation:[[touches anyObject] locationInView:self]];
    }
}


- (void)dealloc {
    [super dealloc];
}


@end
